<template>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <h1>蜗牛AI在线课堂</h1>
                <p>欢迎回来，请登录您的账户</p>
            </div>

            <a-tabs v-model:activeKey="activeTab" centered>
                <a-tab-pane key="user" tab="用户登录">
                    <a-form :model="userForm" :rules="userRules" @finish="handleUserLogin" layout="vertical">
                        <a-form-item label="用户名/邮箱" name="username">
                            <a-input v-model:value="userForm.username" placeholder="请输入用户名或邮箱" size="large">
                                <template #prefix>
                                    <UserOutlined />
                                </template>
                            </a-input>
                        </a-form-item>

                        <a-form-item label="密码" name="password">
                            <a-input-password v-model:value="userForm.password" placeholder="请输入密码" size="large">
                                <template #prefix>
                                    <LockOutlined />
                                </template>
                            </a-input-password>
                        </a-form-item>

                        <a-form-item>
                            <a-checkbox v-model:checked="userForm.remember" name="remember">记住我</a-checkbox>
                            <a class="forgot-link" @click="showForgotPassword">忘记密码？</a>
                        </a-form-item>

                        <a-form-item>
                            <a-button type="primary" html-type="submit" size="large" block :loading="userLoading">
                                登录
                            </a-button>
                        </a-form-item>
                    </a-form>

                    <div class="login-footer">
                        <span>还没有账户？</span>
                        <a @click="$router.push('/register')">立即注册</a>
                    </div>
                </a-tab-pane>

                <a-tab-pane key="admin" tab="管理员登录">
                    <a-form :model="adminForm" :rules="adminRules" @finish="handleAdminLogin" layout="vertical">
                        <a-form-item label="管理员账号" name="username">
                            <a-input v-model:value="adminForm.username" placeholder="请输入管理员账号" size="large">
                                <template #prefix>
                                    <UserOutlined />
                                </template>
                            </a-input>
                        </a-form-item>

                        <a-form-item label="密码" name="password">
                            <a-input-password v-model:value="adminForm.password" placeholder="请输入密码" size="large">
                                <template #prefix>
                                    <LockOutlined />
                                </template>
                            </a-input-password>
                        </a-form-item>

                        <a-form-item>
                            <a-checkbox v-model:checked="adminForm.remember" name="remember">记住我</a-checkbox>
                        </a-form-item>

                        <a-form-item>
                            <a-button type="primary" html-type="submit" size="large" block :loading="adminLoading">
                                管理员登录
                            </a-button>
                        </a-form-item>
                    </a-form>
                </a-tab-pane>
            </a-tabs>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'

import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { adminLogin, userLogin } from '@/api/loginController.ts'
import { EmitFlags } from 'typescript'

const router = useRouter()
const activeTab = ref('user')
const userLoading = ref(false)
const adminLoading = ref(false)

// 用户登录表单
const userForm = reactive({
    username: '',
    password: '',
    remember: false
})

const userRules = {
    username: [
        { required: true, message: '请输入用户名或邮箱', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, message: '密码长度不能少于3位', trigger: 'blur' }
    ]
}

// 管理员登录表单
const adminForm = reactive({
    username: '',
    password: '',
    remember: false
})

const adminRules = {
    username: [
        { required: true, message: '请输入管理员账号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ]
}

// 用户登录
const handleUserLogin = async (values: any) => {
    userLoading.value = true;
    try {
        const { data } = await userLogin(values);
        console.log(data);
        if (data.code === 0) {
            const { token, userId, roleCodes, isAdmin, forcePasswordChange } = data.data;
            // 存储用户信息
            localStorage.setItem('token', token);
            localStorage.setItem('userInfo', JSON.stringify({
                userId,
                username: values.username,
                isAdmin,
                roles: roleCodes,// 存储所有角色
                forcePasswordChange
            }));
            // 如果需要强制修改密码
            if (forcePasswordChange) {
                router.push({
                    path: '/user',
                    query: { forcePasswordChange: 'true', userId: userId }
                });
                message.warning('请先修改您的默认密码');
            } else {

                // 检查用户角色 - 确保不是管理员
                if ((isAdmin || roleCodes.includes('admin')) && !roleCodes.includes('user')) {
                    message.error('纯管理员账号请使用管理员登录入口');
                    return;
                }
                // 如果记住我勾选了，存储用户名和密码
                if (values.remember) {
                    localStorage.setItem('rememberUser', JSON.stringify({
                        username: values.username,

                    }));
                } else {
                    localStorage.removeItem('rememberUser');
                }
                router.push('/');
                message.success('登录成功');
            }
        } else {
            message.error(data.message);
        }
    } catch (error: any) {
        if (error.code === 50001) {
            console.log("error", error);
            const { userId, username, forcePasswordChange, tokenValue } = error.data;
            localStorage.setItem('userInfo', JSON.stringify({
                userId,username, forcePasswordChange
            }));
            localStorage.setItem('token', tokenValue);
            if (forcePasswordChange) {
                // 跳转到用户中心
                router.push({
                    path: '/user',

                    query: { forcePasswordChange: 'true', userId: userId }
                });
            }
        } else {
            message.error(error.response?.data?.message || '登录失败');
        }
    } finally {
        userLoading.value = false;
    }
};

// 管理员登录
const handleAdminLogin = async (values: any) => {
    adminLoading.value = true;
    console.log(values);

    try {
        // 添加 requireAdmin 参数
        const { data } = await adminLogin({ ...values, requireAdmin: true });

        if (data.code === 0) {
            const { token, userId, roleCodes, isAdmin } = data.data;

            localStorage.setItem('token', token);
            localStorage.setItem('userInfo', JSON.stringify({
                userId,
                username: values.username,
                isAdmin,
                roles: roleCodes
            }));
            console.log(localStorage.getItem('userInfo'));

            if (values.remember) {
                localStorage.setItem('rememberUser', JSON.stringify({
                    username: values.username,

                }));
            } else {
                localStorage.removeItem('rememberUser');
            }

            router.push('/admin');
             message.success('登录成功');
        } else {
            message.error(data.message);
        }
    } catch (error: any) {
        console.error('登录错误:', error);
        message.error(error.message);
    } finally {
        adminLoading.value = false;
    }
};

// 页面加载时检查是否有记住的用户信息
const checkRememberedUser = () => {
    const rememberedUser = localStorage.getItem('rememberUser');
    if (rememberedUser) {
        const { username, password } = JSON.parse(rememberedUser);
        if (activeTab.value === 'user') {
            userForm.username = username;
            userForm.remember = true;
        } else if (activeTab.value === 'admin') {
            adminForm.username = username;
            adminForm.remember = true;
        }
    }
};


// 忘记密码
const showForgotPassword = () => {
    message.info('请联系管理员重置密码')
}

watch(() => activeTab.value, (newTab) => {
    checkRememberedUser();  // 每次切换标签时重新检查“记住我”信息
});

onMounted(() => {
    checkRememberedUser();
});
</script>

<style scoped>
/* 原有样式保持不变 */
.login-container {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 24px;
}

.login-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    padding: 48px;
    width: 100%;
    max-width: 480px;
}

.login-header {
    text-align: center;
    margin-bottom: 32px;
}

.login-header h1 {
    color: #333;
    margin-bottom: 8px;
    font-size: 28px;
}

.login-header p {
    color: #666;
    margin: 0;
}

.forgot-link {
    float: right;
    color: #1890ff;
}

.login-footer {
    text-align: center;
    margin-top: 24px;
    color: #666;
}

.login-footer a {
    color: #1890ff;
    margin-left: 4px;
}
</style>
